<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
    <!-- 顶部导航 -->
    <div class="bg-white shadow-sm border-b">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
          <div class="flex items-center space-x-4">
            <el-button 
              type="text" 
              @click="goBack"
              class="text-blue-600 hover:text-blue-800"
            >
              <el-icon class="mr-1">
                <ArrowLeft />
              </el-icon>
              返回
            </el-button>
            <div class="h-6 w-px bg-gray-300"></div>
            <h1 class="text-xl font-bold text-blue-600">AI营销方案生成</h1>
          </div>
          <div class="flex items-center space-x-4">
            <div class="text-sm text-gray-500">
              会话ID: {{ currentSessionId || '未创建' }}
            </div>
            <div class="flex items-center space-x-2">
              <div 
                class="w-2 h-2 rounded-full"
                :class="{
                  'bg-green-500': wsStatus.isConnected,
                  'bg-red-500': !wsStatus.isConnected
                }"
              ></div>
              <span class="text-xs text-gray-500">
                {{ wsStatus.isConnected ? '已连接' : '未连接' }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-6 h-[calc(100vh-4rem)] flex flex-col">
      <!-- 内容展示区 -->
      <div class="flex-1 bg-white rounded-lg shadow-md mb-4 flex flex-col overflow-hidden">
        <!-- 聊天消息区域 -->
        <div 
          ref="messagesContainer"
          class="flex-1 overflow-y-auto p-6 space-y-4"
        >
          <!-- 欢迎消息 -->
          <div v-if="messages.length === 0" class="text-center py-12">
            <div class="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <el-icon :size="40" class="text-blue-600">
                <ChatDotRound />
              </el-icon>
            </div>
            <h3 class="text-lg font-semibold text-gray-900 mb-2">欢迎使用AI营销方案生成</h3>
            <p class="text-gray-600 max-w-md mx-auto">
              我将根据您提交的需求信息，为您生成专业的营销方案。
              您可以随时与我对话，优化和完善方案内容。
            </p>
            <el-button 
              type="primary" 
              class="mt-4"
              @click="startGeneration"
              :loading="isGenerating"
            >
              {{ isGenerating ? '生成中...' : '开始生成营销方案' }}
            </el-button>
          </div>

          <!-- 聊天消息列表 -->
          <div 
            v-for="(message, index) in messages" 
            :key="index"
            class="flex"
            :class="{
              'justify-end': message.role === 'user',
              'justify-start': message.role === 'assistant'
            }"
          >
            <div 
              class="max-w-3xl px-4 py-3 rounded-lg"
              :class="{
                'bg-blue-600 text-white': message.role === 'user',
                'bg-gray-100 text-gray-900': message.role === 'assistant'
              }"
            >
              <!-- 消息头部 -->
              <div class="flex items-center mb-2">
                <div class="flex items-center space-x-2">
                  <div 
                    class="w-6 h-6 rounded-full flex items-center justify-center"
                    :class="{
                      'bg-blue-500': message.role === 'user',
                      'bg-blue-600': message.role === 'assistant'
                    }"
                  >
                    <el-icon :size="14" class="text-white">
                      <User v-if="message.role === 'user'" />
                      <ChatDotRound v-else />
                    </el-icon>
                  </div>
                  <span class="text-sm font-medium">
                    {{ message.role === 'user' ? '您' : 'AI助手' }}
                  </span>
                </div>
                <span 
                  class="text-xs ml-auto"
                  :class="{
                    'text-blue-200': message.role === 'user',
                    'text-gray-500': message.role === 'assistant'
                  }"
                >
                  {{ formatTime(message.timestamp) }}
                </span>
              </div>
              
              <!-- 消息内容 -->
              <div class="prose prose-sm max-w-none">
                <div v-if="message.role === 'assistant'" class="whitespace-pre-wrap">
                  {{ message.content }}
                  <span v-if="message.isStreaming" class="inline-block w-2 h-4 bg-current animate-pulse ml-1"></span>
                </div>
                <div v-else class="whitespace-pre-wrap">
                  {{ message.content }}
                </div>
              </div>
              
              <!-- 消息操作 -->
              <div v-if="message.role === 'assistant' && !message.isStreaming" class="mt-3 flex space-x-2">
                <el-button 
                  size="small" 
                  type="text"
                  @click="copyMessage(message.content)"
                >
                  <el-icon class="mr-1">
                    <CopyDocument />
                  </el-icon>
                  复制
                </el-button>
                <el-button 
                  size="small" 
                  type="text"
                  @click="regenerateResponse(index)"
                >
                  <el-icon class="mr-1">
                    <Refresh />
                  </el-icon>
                  重新生成
                </el-button>
              </div>
            </div>
          </div>
          
          <!-- 加载指示器 -->
          <div v-if="isGenerating && !hasStreamingMessage" class="flex justify-start">
            <div class="bg-gray-100 rounded-lg px-4 py-3">
              <div class="flex items-center space-x-2">
                <el-icon class="animate-spin text-blue-600">
                  <Loading />
                </el-icon>
                <span class="text-gray-600">AI正在思考中...</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 交互输入区 -->
      <div class="bg-white rounded-lg shadow-md p-4">
        <div class="flex space-x-4">
          <div class="flex-1">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              placeholder="请输入您的问题或要求，我会帮您优化营销方案..."
              :disabled="isGenerating"
              @keydown.ctrl.enter="sendMessage"
              class="resize-none"
            />
            <div class="text-xs text-gray-500 mt-1">
              按 Ctrl + Enter 发送消息
            </div>
          </div>
          <div class="flex flex-col space-y-2">
            <el-button 
              type="primary"
              :disabled="!inputMessage.trim() || isGenerating"
              @click="sendMessage"
            >
              <el-icon class="mr-1">
                <Promotion />
              </el-icon>
              发送
            </el-button>
            <el-button 
              v-if="isGenerating"
              type="danger"
              @click="stopGeneration"
            >
              <el-icon class="mr-1">
                <VideoPause />
              </el-icon>
              停止
            </el-button>
          </div>
        </div>
      </div>

      <!-- 操作控制区 -->
      <div class="mt-4 flex justify-between items-center">
        <div class="flex space-x-2">
          <el-button 
            size="small"
            @click="clearChat"
            :disabled="isGenerating"
          >
            <el-icon class="mr-1">
              <Delete />
            </el-icon>
            清空对话
          </el-button>
          <el-button 
            size="small"
            @click="exportChat"
            :disabled="messages.length === 0"
          >
            <el-icon class="mr-1">
              <Download />
            </el-icon>
            导出对话
          </el-button>
        </div>
        <div class="text-sm text-gray-500">
          共 {{ messages.length }} 条消息
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, ChatDotRound, User, CopyDocument, Refresh,
  Loading, Promotion, VideoPause, Delete, Download
} from '@element-plus/icons-vue'
import { useAppStore } from '@/stores'
import { useWebSocket, type StreamMessage } from '@/utils/websocket'

interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
  timestamp: Date
  isStreaming?: boolean
}

const router = useRouter()
const route = useRoute()
const store = useAppStore()
const { client: wsClient, isConnected, startStream, stopStream, sendMessage: wsSendMessage } = useWebSocket()

// 响应式数据
const messages = ref<ChatMessage[]>([])
const inputMessage = ref('')
const isGenerating = ref(false)
const messagesContainer = ref<HTMLElement>()
const currentSessionId = ref<string>('')
const requirementId = ref<string>('')
// WebSocket状态
const wsStatus = reactive({
  isConnected: false,
  reconnectAttempts: 0
})

// 计算属性
const hasStreamingMessage = computed(() => {
  return messages.value.some(msg => msg.isStreaming)
})

// 返回上一页
const goBack = () => {
  router.push({ name: 'requirement' })
}

// 格式化时间
const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 开始生成营销方案
const startGeneration = async () => {
  try {
    isGenerating.value = true
    
    // 创建聊天会话
    let sessionId = currentSessionId.value
    if (!sessionId) {
      console.log('创建新的聊天会话...')
      const sessionResponse = await store.createChatSession(requirementId.value)
      sessionId = sessionResponse.session_id
      currentSessionId.value = sessionId
      console.log('会话创建成功，sessionId:', sessionId)
    }
    
    // 确保sessionId存在
    if (!sessionId) {
      throw new Error('无法获取有效的会话ID')
    }
    
    // 添加系统消息
    const systemMessage: ChatMessage = {
      role: 'assistant',
      content: '',
      timestamp: new Date(),
      isStreaming: true
    }
    messages.value.push(systemMessage)
    scrollToBottom()
    
    console.log('准备开始流式生成，参数:', {
      requirementId: requirementId.value,
      sessionId: sessionId,
      message: '请根据我提交的需求信息生成详细的营销方案'
    })
    
    // 开始流式生成
    startStream(
      requirementId.value,
      sessionId,
      '请根据我提交的需求信息生成详细的营销方案',
      (data: StreamMessage) => {
        handleStreamMessage(data, messages.value.length - 1)
      },
      (error: string) => {
        handleStreamError(error)
      }
    )
    
  } catch (error: any) {
    console.error('开始生成失败:', error)
    ElMessage.error(error.message || '生成失败，请重试')
    isGenerating.value = false
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isGenerating.value) return
  
  const userMessage: ChatMessage = {
    role: 'user',
    content: inputMessage.value.trim(),
    timestamp: new Date()
  }
  
  messages.value.push(userMessage)
  const messageContent = inputMessage.value.trim()
  inputMessage.value = ''
  scrollToBottom()
  
  try {
    isGenerating.value = true
    
    // 确保有有效的sessionId
    let sessionId = currentSessionId.value
    if (!sessionId) {
      console.log('发送消息时创建新的聊天会话...')
      const sessionResponse = await store.createChatSession(requirementId.value)
      sessionId = sessionResponse.session_id
      currentSessionId.value = sessionId
      console.log('会话创建成功，sessionId:', sessionId)
    }
    
    if (!sessionId) {
      throw new Error('无法获取有效的会话ID')
    }
    
    // 添加AI回复消息
    const aiMessage: ChatMessage = {
      role: 'assistant',
      content: '',
      timestamp: new Date(),
      isStreaming: true
    }
    messages.value.push(aiMessage)
    scrollToBottom()
    
    console.log('发送消息，参数:', {
      requirementId: requirementId.value,
      sessionId: sessionId,
      message: messageContent
    })
    
    // 开始流式生成
    startStream(
      requirementId.value,
      sessionId,
      messageContent,
      (data: StreamMessage) => {
        handleStreamMessage(data, messages.value.length - 1)
      },
      (error: string) => {
        handleStreamError(error)
      }
    )
    
  } catch (error: any) {
    console.error('发送消息失败:', error)
    ElMessage.error(error.message || '发送失败，请重试')
    isGenerating.value = false
  }
}

// 处理流式消息
const handleStreamMessage = (data: StreamMessage, messageIndex: number) => {
  const message = messages.value[messageIndex]
  if (!message) return
  
  switch (data.type) {
    case 'start':
      message.content = ''
      message.isStreaming = true
      break
      
    case 'chunk':
      if (data.content) {
        message.content += data.content
        scrollToBottom()
      }
      break
      
    case 'end':
      message.isStreaming = false
      isGenerating.value = false
      scrollToBottom()
      break
      
    case 'error':
      message.isStreaming = false
      message.content += '\n\n[生成过程中出现错误，请重试]'
      isGenerating.value = false
      ElMessage.error(data.error || '生成过程中出现错误')
      break
  }
}

// 处理流式错误
const handleStreamError = (error: string) => {
  console.error('流式生成错误:', error)
  isGenerating.value = false
  ElMessage.error(error)
}

// 停止生成
const stopGeneration = () => {
  stopStream()
  isGenerating.value = false
  
  // 标记最后一条流式消息为完成
  const lastMessage = messages.value[messages.value.length - 1]
  if (lastMessage && lastMessage.isStreaming) {
    lastMessage.isStreaming = false
    lastMessage.content += '\n\n[生成已停止]'
  }
}

// 复制消息
const copyMessage = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 重新生成回复
const regenerateResponse = async (messageIndex: number) => {
  if (isGenerating.value) return
  
  try {
    // 找到对应的用户消息
    let userMessageIndex = messageIndex - 1
    while (userMessageIndex >= 0 && messages.value[userMessageIndex].role !== 'user') {
      userMessageIndex--
    }
    
    if (userMessageIndex < 0) {
      ElMessage.warning('无法找到对应的用户消息')
      return
    }
    
    const userMessage = messages.value[userMessageIndex].content
    
    // 确保有有效的sessionId
    let sessionId = currentSessionId.value
    if (!sessionId) {
      console.log('重新生成时创建新的聊天会话...')
      const sessionResponse = await store.createChatSession(requirementId.value)
      sessionId = sessionResponse.session_id
      currentSessionId.value = sessionId
      console.log('会话创建成功，sessionId:', sessionId)
    }
    
    if (!sessionId) {
      throw new Error('无法获取有效的会话ID')
    }
    
    // 重置AI消息
    const aiMessage = messages.value[messageIndex]
    aiMessage.content = ''
    aiMessage.isStreaming = true
    aiMessage.timestamp = new Date()
    
    isGenerating.value = true
    scrollToBottom()
    
    console.log('重新生成回复，参数:', {
      requirementId: requirementId.value,
      sessionId: sessionId,
      message: userMessage
    })
    
    // 重新开始流式生成
    startStream(
      requirementId.value,
      sessionId,
      userMessage,
      (data: StreamMessage) => {
        handleStreamMessage(data, messageIndex)
      },
      (error: string) => {
        handleStreamError(error)
      }
    )
    
  } catch (error: any) {
    console.error('重新生成失败:', error)
    ElMessage.error(error.message || '重新生成失败')
    isGenerating.value = false
  }
}

// 清空对话
const clearChat = async () => {
  try {
    await ElMessageBox.confirm(
      '确认清空所有对话记录？此操作不可恢复。',
      '确认清空',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    messages.value = []
    store.clearChatMessages()
    ElMessage.success('对话记录已清空')
    
  } catch (error) {
    // 用户取消
  }
}

// 导出对话
const exportChat = () => {
  try {
    const chatContent = messages.value.map(msg => {
      const role = msg.role === 'user' ? '用户' : 'AI助手'
      const time = formatTime(msg.timestamp)
      return `[${time}] ${role}: ${msg.content}`
    }).join('\n\n')
    
    const blob = new Blob([chatContent], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `营销方案对话_${new Date().toISOString().slice(0, 10)}.txt`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    ElMessage.success('对话记录已导出')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 更新WebSocket状态
const updateWebSocketStatus = () => {
  const status = wsClient.getConnectionStatus()
  wsStatus.isConnected = status.isConnected
  wsStatus.reconnectAttempts = status.reconnectAttempts
}

// 组件挂载
onMounted(async () => {
  // 获取需求ID
  requirementId.value = route.query.requirement_id as string || ''
  
  if (!requirementId.value) {
    ElMessage.warning('缺少需求ID，请重新提交需求')
    router.push({ name: 'requirement' })
    return
  }
  
  // 更新WebSocket状态
  updateWebSocketStatus()
  
  // 定期更新WebSocket状态
  const statusInterval = setInterval(updateWebSocketStatus, 1000)
  
  // 清理定时器
  onUnmounted(() => {
    clearInterval(statusInterval)
  })
})

// 组件卸载时清理
onUnmounted(() => {
  if (isGenerating.value) {
    stopGeneration()
  }
})
</script>

<style scoped>
.animate-pulse {
  animation: pulse 1s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.prose {
  line-height: 1.6;
}

.prose p {
  margin-bottom: 0.5em;
}

.prose p:last-child {
  margin-bottom: 0;
}
</style>